<template>
	<view class="container pageColor">
		<tn-nav-bar :fixed="true" :isBack="false" fixed :alpha="isalpha" :bottomShadow="true" backgroundColor="#ffffff">
			<view class="tn-flex tn-flex-col-center tn-flex-row-center ">
				<text class="tn-text-lg tn-text-bold tn-color-black">票据列表</text>
			</view>
		</tn-nav-bar>
		<view class="pageContent" :style="{paddingTop: vuex_custom_bar_height + 'px'}">

			<view class="tn-margin">
				<view class="tn-text-bold">
					票据总额
				</view>
				<view class="tn-margin-sm" style="font-size: 50rpx;color: #301ff9;height: 50rpx;">
					￥{{total}}
				</view>
				<view class="" style="width: 100%;height: 380rpx;">
					<qiun-data-charts type="ring" :opts="opts" :chartData="chartData" />
				</view>
			</view>

			<z-paging ref="paging" v-model="list" @query="queryList" use-page-scroll :fixed="false"
				:auto-clean-list-when-reload="false" :auto-scroll-to-top-when-reload="false" :scrollable="false"
				:show-scrollbar="false" auto-show-back-to-top="false" loading-full-fixed="false">
				<view class="card" v-for="item in list" @click="updateRow(item)">
					<view class="pt">
						{{item.pt}}
					</view>
					<view class="tn-flex tn-flex-row-between tn-flex-row-center tn-flex-col-center">
						<view class="tn-flex tn-flex-direction-column ">
							<view class="tn-text-bold tn-text-xl">
								￥{{formaNum(item.je)}}
							</view>
							<view class="tn-color-gray">
								票据金额
							</view>
						</view>
						<view class="tn-flex tn-flex-direction-column tn-flex-row-center">
							<view class="">
								{{item.dqr}}
							</view>
							<view class="tn-color-gray" v-if="item.syts>0">
								{{item.syts}}天后到期
							</view>
							<view class="tn-color-orangered" v-if="item.syts<=0">
								已过期
							</view>
						</view>

					</view>
					<view class="cdr tn-flex tn-flex-row-between tn-flex-col-center">
						<view class="">
							承兑人：{{item.klf}}
						</view>
						<view class="" v-if="isHaveAdmin" @click.stop="deleteItem(item.pjh)">
							<text class="tn-icon-delete"></text>
						</view>
					</view>
				</view>
			</z-paging>
		</view>

		<view class="tn-tabbar-height"></view>



		<tn-popup v-model="show" mode="bottom" borderRadius="20">
			<view class="title tn-text-center tn-margin tn-text-bold tn-text-lg tn-margin-top-lg">
				票据号：{{model.pjh}}
			</view>

			<view class="tn-padding-sm tn-margin-sm " style="border: 1px solid #e3e3e3;border-radius: 10px;">
				<tn-form :model="model" ref="form" :errorType="errorType" :labelPosition="labelPosition" disabled
					:labelWidth="labelWidth" :labelAlign="labelAlign">
					<tn-form-item label="平台:" prop="pt" leftIcon="calendar" :labelPosition="labelPosition"
						:labelAlign="labelAlign">
						<tn-input v-model="model.pt" type="select" placeholder="请输入平台" :border="border" @click="ptClick"></tn-input>
					</tn-form-item>
					<tn-form-item label="金额:" prop="je" leftIcon="money" :labelPosition="labelPosition"
						:labelAlign="labelAlign">
						<tn-input v-model="model.je" :disabled="!isHaveAdmin" type="text" placeholder="请输入金额" :border="border"></tn-input>
					</tn-form-item>
					<tn-form-item label="到期日:" prop="dqr" leftIcon="calendar" :labelPosition="labelPosition"
						:labelAlign="labelAlign">
						<tn-input v-model="model.dqr" type="select" placeholder="请输入到期日" :border="border" @click="dqrClick"></tn-input>
					</tn-form-item>
					<tn-form-item label="剩余天数:" prop="syts" leftIcon="calendar" :labelPosition="labelPosition"
						:labelAlign="labelAlign">
						<tn-input v-model="model.syts" disabled type="number" placeholder="请输入剩余天数" :border="border"></tn-input>
					</tn-form-item>
					<tn-form-item label="开立方:" prop="klf" leftIcon="my-reduce" :labelPosition="labelPosition"
						:labelAlign="labelAlign">
						<tn-input v-model="model.klf" :disabled="!isHaveAdmin" type="text" placeholder="请输入开立方" :border="border"></tn-input>
					</tn-form-item>
				</tn-form>
			</view>
			<view class="tn-padding-sm tn-margin-sm tn-text-center" v-if="isHaveAdmin">
				<tn-button fontBold blockRepeatClick='true' plain width="100%" backgroundColor="#35b2ff"
					@click="submitForm" fontColor="#080808">提交信息</tn-button>
			</view>
		</tn-popup>
		<!-- 悬浮按钮 -->
		<uni-fab ref="fab" v-if="isHaveAdmin" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			:direction="direction" @trigger="trigger" @fabClick="fabClick" />
			
		<!-- 选择日期 -->
		<tn-picker mode="time" v-model="showDqr" :params="params" @confirm="confirmDqr"></tn-picker>
		<!-- 选择平台 -->
		<tn-select v-model="showPt" mode="single" :list="ptList" @confirm="confirmPt"></tn-select>
		<!-- 加载动画 -->
		<zero-loading v-if="loading" mask="true" maskDark="false" type="circle" maskOpacity="1"
			color="#aaffff"></zero-loading>
	</view>
</template>
<script>
	import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
	import m_excel from '../../uni_modules/m-excel/m-excel/js_sdk';
	const db = uniCloud.database();
	const dbCollectionName = 'pjxx';
	const dbCmd = db.command;
	export default {
		mixins: [ZPMixin],
		data() {
			return {
				// 显示日期控件
				showDqr: false,
				showPt: false,
				// 只显示年月日
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				ptList: [
					{
						label: '商票',
						value: '商票'
					},
					{
						label: '联易融',
						value: '联易融'
					},
					{
						label: '航信',
						value: '航信'
					},
					{
						label: '桐信',
						value: '桐信'
					},
					{
						label: '能信',
						value: '能信'
					},
					{
						label: '云信',
						value: '云信'
					},
					{
						label: '快信',
						value: '快信'
					},
					{
						label: '讯易链',
						value: '讯易链'
					},
				],
				isHaveAdmin: false,
				list: [],
				show: false,
				modelId: null,
				model: null,
				labelWidth: 180,
				labelPosition: 'left',
				labelAlign: 'right',
				openid: null,
				total: 0,
				chartData: {},
				title: 'uni-fab',
				directionStr: '垂直',
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				is_color_type: false,
				content: [{
						iconPath: '/static/images/export.png',
						selectedIconPath: '/static/images/export.png',
						text: '导入',
						active: false
					},
					{
						iconPath: '/static/images/addto.png',
						selectedIconPath: '/static/images/addto.png',
						text: '新增',
						active: false
					}
				],
				opts: {
					rotate: false,
					rotateLock: false,
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [10, 5, 5, 5],
					dataLabel: true,
					enableScroll: false,
					legend: {
						show: true,
						position: "bottom",
						lineHeight: 20
					},
					title: {
						name: "",
						fontSize: 10,
						color: "#6356fa"
					},
					subtitle: {
						name: "",
						fontSize: 10,
						color: "#7cb5ec"
					},
					extra: {
						ring: {
							ringWidth: 60,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: false,
							borderWidth: 3,
							borderColor: "#FFFFFF"
						}
					}
				}
			}
		},
		watch: {
			'vuex_user': {
				handler(value) {
					// 如果user发生变化发生改变，重新初始化选项列表信息

				},
				deep: true,
			}
		},
		onPageScroll(e) {
			if (e.scrollTop > 80) {
				this.isalpha = false
			} else {
				this.isalpha = true
			}
		},
		onLoad() {
			this.getOpenid()
			this.getServerData();
		},
		onReady() {

		},
		methods: {
			ptClick(){
				if(this.isHaveAdmin){
					this.showPt = true
				}
			},
			dqrClick(){
				if(this.isHaveAdmin){
					this.showDqr = true
				}
			},
			trigger(e) {
				console.log(e)
				// this.content[e.index].active = !e.item.active
				if(e.index == 0){
					this.uploadExcel()
				} else {
					this.goInfo()
				}
			},
			fabClick() {
				
			},
			/**
			 * 格式化数字
			 * @param {Object} numer
			 */
			formaNum(numer) {
				return numer.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
			},
			getServerData() {
				uniCloud.callFunction({
					name: 'getTotal',
					data: {},
					success: (res) => {
						console.log('返回数据为', res.result)
						this.total = this.formaNum(res.result.total)
					},
					fail: () => {
						console.log('获取失败')
					}
				})
				uniCloud.callFunction({
					name: 'getSumByType',
					data: {},
					success: (res) => {
						console.log('返回数据为', res.result)
						let chartdata = {
							series: [{
								data: res.result
							}]
						};
						this.chartData = JSON.parse(JSON.stringify(chartdata));
					},
					fail: () => {
						console.log('获取失败')
					}
				})
			},
			// 获取openid
			getOpenid() {
				let that = this
				uni.login({
					provider: "weixin",
					success: function(res) {
						uniCloud.callFunction({
							name: 'getOpenid',
							data: {
								code: res.code
							},
							success: (res) => {
								console.log('Openid为', res.result)
								// this.$tn.vuex('vuex_openid', res.result)
								that.openid = res.result
								db.collection("role").get().then(resc => {
									let ishave = resc.result.data.filter(v => v.openid == res.result)
									console.log("ishave",ishave);
									if(ishave.length>0){
										that.isHaveAdmin = true
									}
									
								})
							},
							fail: () => {
								console.log('获取失败')
							}
						})
					},
				});
			},
			deleteItem(pjh) {
				let that = this
				uni.showModal({
					title: '提示',
					content: `确认删除${pjh}的数据吗`,
					success: function(res) {
						if (res.confirm) {
							db.collection(dbCollectionName).where({
								pjh: pjh
							}).remove()
							that.$refs.paging.reload(true);
							that.getServerData()
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})

			},
			/**
			 * 上传excel
			 */
			uploadExcel() {
				uni.showLoading({
					title: '上传中...'
				})
				m_excel.read().then((e) => {
					if (e.success == 1) {
						let pjhs = this.list.map(v => v.pjh)
						// 删除数据
						db.collection(dbCollectionName).where({
							pjh: dbCmd.in(pjhs)
						}).remove().then(res => {
							this.total = 0
							let pushList = []
							e.data.forEach(v => {
								let param = {
									openid: this.openid + '',
									pjh: v.票据号 + '',
									klf: v.开立方 + '',
									pt: v.平台 + '',
									je: v.金额 + '',
									dqr: v.到期日 + '',
									syts: v.天 + '',
									cjsj: v.今天日期 + '',
									ll: v.利率 + '',
									tx: v.贴息 + '',
									txje: v.贴现金额 + '',
									bz: v.备注 + ''
								}
								pushList.push(param)
							})
							console.log(pushList);
							db.collection(dbCollectionName).add(pushList).then(res => {
								console.log(res);
								uni.hideLoading()
								this.$refs.paging.reload(true);
								this.getServerData()
							})
						})

					} else {
						console.log(e)
						uni.hideLoading()
					}
				})
			},
			/**
			 * 更新数据
			 * @param {Object} row
			 */
			updateRow(row) {
				this.show = true
				this.model = row
				this.modelId = row._id
				delete this.model._id
			},
			/**
			 * 修改
			 */
			submitForm() {
				return db.collection(dbCollectionName).doc(this.modelId).update(this.model).then((res) => {
					this.tool.toastTip('修改成功')
					this.$refs.paging.reload(true);
					this.getServerData()
					this.show = false
				}).catch((err) => {
					this.tool.toastTip('修改失败')
				})
			},
			/**
			 * @param {Object} pageNo
			 * @param {Object} pageSize
			 * @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用this.$refs.paging.reload()即可
			 */
			queryList(pageNo, pageSize) {
				db.collection(dbCollectionName).skip((pageNo - 1) * pageSize).limit(pageSize).get().then((
					res) => {
					const data = res.result.data
					if (data) {
						this.$refs.paging.complete(data);
					}
				}).catch((err) => {
					this.tool.toastTip('请求失败')
				}).finally(() => {
					uni.hideLoading()
				})

			},
			goInfo() {
				uni.navigateTo({
					url: "/pageHome/shome?openid=" + this.openid
				})
			},
			
			/**
			 * 确认到期日
			 */
			confirmDqr(e) {
				console.log(e);
				this.model.dqr = e.year + '/' + e.month + '/' + e.day
				this.model.syts = this.handlerSyts(this.model.dqr) + ''
			},
			/**
			 * 确认到期日
			 */
			confirmPt(e) {
				this.model.pt = e[0].value
			},
			/**
			 * 计算天数
			 * @param {Object} rq
			 */
			handlerSyts(rq){
				let targetDate = new Date(rq)
				// 计算距离目标日期的天数
				const now = new Date();
				// 将时间部分重置为午夜，避免时区问题
				const nowMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const targetMidnight = new Date(targetDate.getFullYear(), targetDate.getMonth(),targetDate.getDate());
				// 计算时间差（毫秒）
				const diff = targetMidnight - nowMidnight;
				// 转换为天
				let syts = Math.ceil(diff / (1000 * 60 * 60 * 24));
				return syts
			}
			
		}
	}
</script>
<style lang="less" scoped>
	.container {
		width: 100%;
		font-family: PingFang SC, PingFang SC;

		.logo {
			width: 55rpx;
			height: 55rpx;
		}

		.pageContent {
			// padding: 0 40rpx;

			.card {
				margin: 45rpx;
				padding: 30rpx 20rpx;
				border-radius: 20rpx;
				box-shadow: 0 0 5rpx #ccc;
				position: relative;

				.pt {
					background-color: white;
					z-index: 999;
					position: absolute;
					border-radius: 10rpx;
					color: #ee86cc;
					font-weight: 600;
					border: 1px solid #ee86cc;
					text-align: center;
					padding: 6rpx 15rpx;
					/* 垂直居中（与高度一致） */
					overflow: hidden;
					white-space: nowrap;
					left: -25rpx;
					top: -30rpx;
					font-size: 28rpx;
					/* 根据需要调整字体大小 */
				}

				.cdr {
					margin-top: 5rpx;
				}
			}


		}
	}


	/* 悬浮 */
	.tnxuanfu {
		animation: suspension 3s ease-in-out infinite;
	}

	@keyframes suspension {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-0.8rem);
		}
	}

	/* 悬浮按钮 */
	.button-shop {
		width: 90rpx;
		height: 90rpx;
		display: flex;
		flex-direction: row;
		position: fixed;
		/* bottom:200rpx;
	    right: 20rpx; */
		left: 5rpx;
		top: 5rpx;
		z-index: 1001;
		border-radius: 100px;
		opacity: 0.9;
	}


	/* 按钮 */
	.edit {
		bottom: 300rpx;
		right: 75rpx;
		position: fixed;
		z-index: 9999;
	}


	.pa,
	.pa0 {
		position: absolute
	}

	.pa0 {
		left: 0;
		top: 0
	}


	.bg0 {
		width: 100rpx;
		height: 100rpx;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.bg1 {
		width: 100%;
		height: 100%;
	}




	.hx-box {
		top: 50%;
		left: 50%;
		width: 100rpx;
		height: 100rpx;
		transform-style: preserve-3d;
		transform: translate(-50%, -50%) rotateY(75deg) rotateZ(10deg);
	}

	.hx-box .pr {
		width: 100rpx;
		height: 100rpx;
		transform-style: preserve-3d;
		animation: hxz 20s linear infinite;
	}

	@keyframes hxz {
		0% {
			transform: rotateX(0deg);
		}

		100% {
			transform: rotateX(-360deg);
		}
	}



	.hx-box .pr .pa0 {
		width: 100rpx;
		height: 100rpx;
		/* border: 4px solid #5ec0ff; */
		border-radius: 1000px;
	}

	.hx-box .pr .pa0 .span {
		display: block;
		width: 100%;
		height: 100%;
		background: url(https://resource.tuniaokj.com/images/cool_bg_image/arc4.png) no-repeat center center;
		background-size: 100% 100%;
		animation: hx 4s linear infinite;
	}

	@keyframes hx {
		to {
			transform: rotate(360deg);
		}
	}

	.hx-k1 {
		transform: rotateX(-60deg) rotateZ(-60deg)
	}

	.hx-k2 {
		transform: rotateX(-30deg) rotateZ(-30deg)
	}

	.hx-k3 {
		transform: rotateX(0deg) rotateZ(0deg)
	}

	.hx-k4 {
		transform: rotateX(30deg) rotateZ(30deg)
	}

	.hx-k5 {
		transform: rotateX(60deg) rotateZ(60deg)
	}

	.hx-k6 {
		transform: rotateX(90deg) rotateZ(90deg)
	}


	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 50rpx;
		height: calc(40rpx + env(safe-area-inset-bottom) / 2);
		height: calc(40rpx + constant(safe-area-inset-bottom));
	}
</style>